//
//  String+hex.swift
//  GRVoice
//
//  Created by tucici on 2021/10/12.
//  Copyright © 2021 国瑞语音. All rights reserved.
//

import Foundation
import UIKit

//MARK: - 十六进制字符串转换成颜色
extension String
{
    
    /// 将十六进制颜色转换成UIColor
    /// - Returns: UIColor
    func color() -> UIColor
    {
        self.color(1.0)
    }
    
    /// 将十六进制颜色转换成UIColor
    /// - Parameter alpha: 透明值
    /// - Returns: UIColor
    func color(_ alpha : Float) -> UIColor
    {
        var cString = self.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        if (cString.count < 6)
        {
            return .white
        }
        if cString.hasPrefix("0X")
        {
            cString = cString[2...cString.count]
        }
        if cString.hasPrefix("#")
        {
            cString = cString[1...cString.count]
        }
        if cString.count != 6
        {
            return .white
        }
        
        //R.G.B
        let rString = cString[0...1]
        let gString = cString[2...3]
        let bString = cString[4...5]
        
        //存储转换后的数值
        var r : UInt64 = 0, g : UInt64  = 0, b : UInt64 = 0
        Scanner(string: rString).scanHexInt64(&r)
        Scanner(string: gString).scanHexInt64(&g)
        Scanner(string: bString).scanHexInt64(&b)
        return UIColor(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255.0, alpha:CGFloat(alpha))
    }
    
    /// 获取某个下标的字符
    subscript(of index : Int) -> String
    {
        if index < 0 || index >= self.count
        {
            return ""
        }
        let s = self as NSString
        return s.substring(with: NSMakeRange(index, 1)) as String
    }
    /// 获取[1...3]的字符
    subscript( r : ClosedRange<Int>) -> String
    {
        let start = index(startIndex, offsetBy:max(r.lowerBound, 0))
        let end = index(startIndex, offsetBy: min(r.upperBound, count - 1))
        return String(self[start...end])
    }
    
    /// 截取字符
    /// - Parameters:
    ///   - start: 开始下标
    ///   - count: 截取长度
    /// - Returns: 字符串
    func subString(_ start : Int, _ count : Int) -> String
    {
        let startIndex = index(startIndex, offsetBy:max(start, 0))
        let endIndex = index(startIndex, offsetBy:min(start + count, count))
        return String(self[startIndex...endIndex])
    }
    
    
    /// 字符串不足指定的位数时候，自动补全
    /// - Parameters:
    ///   - count: 指定显示的位数
    ///   - addString: 自动补全的字符串
    /// - Returns: 返回补全后的字符串，例如000001
    func fixString(_ count : Int, _ addString : String)->String
    {
        var temp = self
        for _ in 0..<(count-self.count)
        {
            temp = "\(addString)"+temp
        }
        return temp
    }
}

//MARK: - 字符串转int
extension String
{
    func intValue() -> Int
    {
        return Int((self as NSString).intValue)
    }
    
    func boolValue()->Bool
    {
        assert(self.isNumber(),"\(self)不是一个数字")
        return Bool((self as NSString).boolValue)
    }
    func floatValut() -> CGFloat
    {
        return CGFloat((self as NSString).floatValue)
    }
}

//MARK: - 字符串的一些判断
extension String
{
    
    /// 是否纯数字
    func isNumber() -> Bool
    {
        let numRegex = "[0-9]*"
        let pre : NSPredicate = NSPredicate(format: "SELF MATCHES %@",numRegex)
        return pre.evaluate(with: self)
    }
    ///是否是纯汉字
    func isChinese()-> Bool
    {
        let match = "(^[\u{4e00}-\u{9fa5}]+$)"
        let pre : NSPredicate = NSPredicate(format: "SELF MATCHES %@",match)
        return pre.evaluate(with: self)
    }
    ///是否是邮箱
    func isEmail()->Bool{
        let match = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let pre : NSPredicate = NSPredicate(format: "SELF MATCHES %@",match)
        return pre.evaluate(with: self)
    }
    ///是否空的字符串
    func isNull() -> Bool
    {
        if self.isKind(of:NSString.classForCoder()){
            return self.count == 0
        }
        for i in 0..<self.count
        {
            if (self[of:i] == " ") ==  false {
                return false
            }
        }
        return true
    }
    
    ///是否整数
    func isInt() -> Bool {
        let scan: Scanner = Scanner(string:self)
        var val:Int = 0
        return scan.scanInt(&val) && scan.isAtEnd
    }
}

//MARK: - 日期
extension String
{
    ///时间戳(字符串形式)俺需要的格式，转换成日期格式(MM/dd，或者yy/MM/dd/)
    func transToDate(_ format : String)->String
    {
        let timeInterval = TimeInterval(self.intValue())
        let date = Date(timeIntervalSince1970: timeInterval)
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = format
        return dateformatter.string(from: date)
    }
    
    
    /// 日期形式转换成时间戳
    /// - Parameter format: 日期形式MM/dd，或者yy/MM/dd/
    func transToStamp(_ format:String)->Int
    {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from:self)
        return Int(date?.timeIntervalSince1970 ?? 0)
    }
    
    ///具体秒数（非时间戳）转换成24小时格式
    func secTranToTime()->String
    {
        let num = self.intValue()
        let min = num / 60 % 60
        let second = num % 60
        let hour = num / 3600
        return String(format:"%.2ld:%.2ld:%.2ld", hour,min,second)
    }
}

//MARK: - 十进制、十六进制转换
extension String
{
    //MARK: - 十六进制转换成十进制
    ///十六进制转换成十进制
    func toDecimal()-> Int
    {
        var sum = 0
        let str:String = self.uppercased()
        for i in str.utf8{
            sum = sum * 16 + Int(i) - 48//0-9:从48开始
            if i >= 65{//a-z:从65开始
                sum -= 7
            }
        }
        
        ///去除。“-”符号
        if sum > Int32.max {
            let realNum = sum - 1
            let negation = ~realNum
            sum = Int(-Int32(negation & 0xff))
        }
        return sum
    }
    
    //MARK: - 16进制字符串转data
    func hexadecimal() -> Data? {
        var data = Data(capacity: self.count / 2)
        
        let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
        regex.enumerateMatches(in: self, range: NSMakeRange(0, utf16.count)) { match, flags, stop in
            let byteString = (self as NSString).substring(with: match!.range)
            var num = UInt8(byteString, radix: 16)!
            data.append(&num, count: 1)
        }
        
        guard data.count > 0 else { return nil }
        
        return data
    }
    
}

extension String
{
    ///富文本
    func attri(_ font:UIFont, _ color:UIColor)->NSMutableAttributedString
    {
        return NSMutableAttributedString(string:self, attributes:[.font:font, .foregroundColor:color])
    }
    
    func kjson()->String
    {
        var s = self
        s = s.replacingOccurrences(of: "[", with: "")
        s = s .replacingOccurrences(of:"]", with: "")
        s = s.replacingOccurrences(of: "\"", with: "")
        return s
    }
}

